package tcp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer implements Runnable {

    private Socket client; //客户端的连接对象。

    public MyServer(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        //输入流：负责获得客户端发来的消息。
        BufferedReader input = null;
        //输入流：负责从控制台获得用户输入的字符串。
        BufferedReader in = null;
        //输出流：负责给客户端发消息。(因为给屏幕输出，所以应该使用PrintStream)
        PrintStream output = null;
        boolean flag = true;
        try {
            //InputStreamReader字节流转换为字符流
            input = new BufferedReader(new InputStreamReader(client.getInputStream()));
            in = new BufferedReader(new InputStreamReader(System.in));
            output = new PrintStream(client.getOutputStream());

            while (flag) {
                //获得客户端发来的字符串
                String msg = input.readLine();
                //这三种情况，都认为是结束线程
                if (msg == null || "".equals(msg) || "bye".equals(msg)) {
                    flag = false;
                } else {
                    System.out.println(msg);
                    //发送消息给客户端
                    System.out.println("请输入内容：");
                    msg = in.readLine();
                    if (msg == null || "".equals(msg) || "bye".equals(msg)) {
                        flag = false;
                    } else {
                        output.println("服务器：" + msg);
                    }
                }
            }
            input.close();
            output.close();
            client.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //创建一个ServerSocket.
        boolean flag = true;
        ServerSocket server = null;
        try {
            //启动服务
            server = new ServerSocket(9999);
            //接收客户端的请求,是阻塞方法
            while (flag) {
                System.out.println("服务器已经启动，等待客户端的请求....");
                Socket client = server.accept();
                //开启一个线程和客户端聊天
                new Thread(new MyServer(client)).start();  //创建了一个服务器对象启动一个线程
            }
            System.out.println("服务器已经关闭....");
            server.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
